// Asset detail page interactions (images, files, batch mode, previews)
// Requires Bootstrap 5 and Django CSRF token present in the page.

(function(){
  'use strict';

  // Utilities
  function getCsrfToken() {
    var el = document.querySelector('[name=csrfmiddlewaretoken]');
    if (el && el.value) return el.value;
    var m = document.cookie.match(/(^|;\s*)csrftoken=([^;]+)/);
    return m ? decodeURIComponent(m[2]) : '';
  }

  function confirmAndSubmit(formEl, message) {
    if (!formEl.id) formEl.id = 'autoForm_' + Math.random().toString(36).slice(2, 9);
    if (!document.body.contains(formEl)) document.body.appendChild(formEl);

    const tmpBtn = document.createElement('button');
    tmpBtn.type = 'button';
    tmpBtn.style.display = 'none';
    tmpBtn.setAttribute('data-confirm', message || '确定要执行此操作吗？');
    tmpBtn.setAttribute('data-submit-form', '#' + formEl.id);
    document.body.appendChild(tmpBtn);
    tmpBtn.click();
    setTimeout(() => { try { tmpBtn.remove(); } catch(e){} }, 5000);
  }

  // State
  let batchMode = false;
  let lastFocusedEl = null; // for focus restore after modals

  function getCurrentImageCount() {
    const fromBody = parseInt(document.body.getAttribute('data-asset-image-count') || 'NaN', 10);
    if (!Number.isNaN(fromBody)) return fromBody;
    const hidden = document.querySelector('input[name="asset_image_count"]');
    const v = hidden ? parseInt(hidden.value || '0', 10) : 0;
    return Number.isNaN(v) ? 0 : v;
  }

  // Image modal preview
  window.showImageModal = function(imageUrl, title) {
    if (batchMode) return;
    const modalEl = document.getElementById('imageModal');
    if (!modalEl) return;
    const modal = bootstrap && bootstrap.Modal ? new bootstrap.Modal(modalEl) : null;
    const modalImage = document.getElementById('modalImage');
    const modalTitle = document.getElementById('imageModalLabel');
    if (modalImage) {
      modalImage.src = imageUrl;
      modalImage.alt = title || '';
    }
    if (modalTitle) modalTitle.textContent = title || '资产图片';
    if (modal) {
      // focus management
      lastFocusedEl = document.activeElement;
      modalEl.addEventListener('shown.bs.modal', function(){
        const closeBtn = modalEl.querySelector('.btn-close');
        (closeBtn || modalEl).focus();
      }, { once: true });
      modalEl.addEventListener('hidden.bs.modal', function(){
        if (lastFocusedEl && typeof lastFocusedEl.focus === 'function') lastFocusedEl.focus();
      }, { once: true });
      modal.show();
    }
  };

  // Image actions
  window.editImageInfo = function(imageId, title, description) {
    const idEl = document.getElementById('editImageId');
    const titleEl = document.getElementById('editImageTitle');
    const descEl = document.getElementById('editImageDescription');
    if (idEl) idEl.value = imageId;
    if (titleEl) titleEl.value = title || '';
    if (descEl) descEl.value = description || '';
    const modalEl = document.getElementById('editImageModal');
    if (modalEl && bootstrap && bootstrap.Modal) {
      lastFocusedEl = document.activeElement;
      const modal = new bootstrap.Modal(modalEl);
      modalEl.addEventListener('shown.bs.modal', function(){
        (titleEl || modalEl).focus();
      }, { once: true });
      modalEl.addEventListener('hidden.bs.modal', function(){
        if (lastFocusedEl && typeof lastFocusedEl.focus === 'function') lastFocusedEl.focus();
      }, { once: true });
      modal.show();
    }
  };

  window.setPrimaryImage = function(imageId) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/asset/${document.body.getAttribute('data-asset-id')}/set-primary-image/`;
    const token = getCsrfToken();
    form.innerHTML = `
      <input type="hidden" name="csrfmiddlewaretoken" value="${token}">
      <input type="hidden" name="image_id" value="${imageId}">
    `;
    confirmAndSubmit(form, '确定要将此图片设为主图片吗？');
  };

  window.deleteImage = function(imageId, title) {
    const imageTitle = title || '未命名图片';
    const currentImageCount = getCurrentImageCount();
    let msg = `确定要删除图片 "${imageTitle}" 吗？\n\n`;
    msg += `• 此操作不可撤销\n`;
    if (currentImageCount) msg += `• 删除后还剩 ${currentImageCount - 1} 张图片\n`;

    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/asset/${document.body.getAttribute('data-asset-id')}/delete-image/`;
    const token = getCsrfToken();
    form.innerHTML = `
      <input type="hidden" name="csrfmiddlewaretoken" value="${token}">
      <input type="hidden" name="image_id" value="${imageId}">
    `;
    confirmAndSubmit(form, msg);
  };

  // File actions
  window.editFileInfo = function(fileId, title, description) {
    const idEl = document.getElementById('editFileId');
    const titleEl = document.getElementById('editFileTitle');
    const descEl = document.getElementById('editFileDescription');
    if (idEl) idEl.value = fileId;
    if (titleEl) titleEl.value = title || '';
    if (descEl) descEl.value = description || '';
    const modalEl = document.getElementById('editFileModal');
    if (modalEl && bootstrap && bootstrap.Modal) {
      lastFocusedEl = document.activeElement;
      const modal = new bootstrap.Modal(modalEl);
      modalEl.addEventListener('shown.bs.modal', function(){
        (titleEl || modalEl).focus();
      }, { once: true });
      modalEl.addEventListener('hidden.bs.modal', function(){
        if (lastFocusedEl && typeof lastFocusedEl.focus === 'function') lastFocusedEl.focus();
      }, { once: true });
      modal.show();
    }
  };

  window.deleteFile = function(fileId, title) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/asset/${document.body.getAttribute('data-asset-id')}/delete-file/`;
    const token = getCsrfToken();
    form.innerHTML = `
      <input type="hidden" name="csrfmiddlewaretoken" value="${token}">
      <input type="hidden" name="file_id" value="${fileId}">
    `;
    const msg = `确定要删除文件 "${title || ''}" 吗？此操作不可撤销。`;
    confirmAndSubmit(form, msg);
  };

  // Batch mode
  window.toggleBatchMode = function() {
    batchMode = !batchMode;
    const batchToolbar = document.getElementById('batchToolbar');
    const batchCheckboxes = document.querySelectorAll('.batch-checkbox');
    const normalActions = document.querySelectorAll('.normal-actions');
    const primaryBadges = document.querySelectorAll('.primary-badge');

    if (batchToolbar) batchToolbar.style.display = batchMode ? 'block' : 'none';
    batchCheckboxes.forEach(cb => cb.style.display = batchMode ? 'block' : 'none');
    normalActions.forEach(a => a.style.display = batchMode ? 'none' : 'block');
    primaryBadges.forEach(b => b.style.display = batchMode ? 'none' : 'block');

    if (!batchMode) {
      document.querySelectorAll('.image-checkbox').forEach(cb => { cb.checked = false; });
      if (typeof updateBatchSelection === 'function') updateBatchSelection();
    }
  };

  window.updateBatchSelection = function() {
    const selectedCheckboxes = document.querySelectorAll('.image-checkbox:checked');
    const selectedCount = selectedCheckboxes.length;
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    const selectedCountSpan = document.getElementById('selectedCount');
    if (selectedCountSpan) selectedCountSpan.textContent = selectedCount;
    if (batchDeleteBtn) batchDeleteBtn.disabled = selectedCount === 0;

    document.querySelectorAll('.image-card').forEach(card => {
      const checkbox = card.querySelector('.image-checkbox');
      if (checkbox && checkbox.checked) {
        card.style.border = '2px solid #007bff';
        card.style.boxShadow = '0 0 10px rgba(0,123,255,0.3)';
      } else {
        card.style.border = '';
        card.style.boxShadow = '';
      }
    });
  };

  window.batchDeleteImages = function() {
    const selectedCheckboxes = document.querySelectorAll('.image-checkbox:checked');
    const selectedCount = selectedCheckboxes.length;
    if (selectedCount === 0) {
      alert('请先选择要删除的图片');
      return;
    }
    const currentImageCount = parseInt(document.body.getAttribute('data-asset-image-count') || '0', 10);
    const selectedIds = Array.from(selectedCheckboxes).map(function (cb) { return cb.value; });
    let msg = `确定要删除选中的 ${selectedCount} 张图片吗？\n\n`;
    msg += `• 此操作不可撤销\n`;
    if (currentImageCount) msg += `• 删除后还剩 ${currentImageCount - selectedCount} 张图片\n`;

    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/asset/${document.body.getAttribute('data-asset-id')}/batch-delete-images/`;
    const token = getCsrfToken();
    let formHTML = `<input type="hidden" name="csrfmiddlewaretoken" value="${token}">`;
    selectedIds.forEach(id => { formHTML += `<input type=\"hidden\" name=\"image_ids\" value=\"${id}\">`; });
    form.innerHTML = formHTML;
    confirmAndSubmit(form, msg);
  };

  // File preview modal (PDF inline) with robust type detection
  function isLikelyPdfByUrl(url){
    return /\.pdf(\?|#|$)/i.test(url || '');
  }

  async function detectPdfByHead(url){
    try {
      const res = await fetch(url, { method: 'HEAD', credentials: 'same-origin' });
      const ct = res.headers.get('Content-Type') || res.headers.get('content-type') || '';
      return ct.toLowerCase().indexOf('application/pdf') !== -1;
    } catch (e) {
      return false;
    }
  }

  function openPdfInModal(url, title){
    const modalEl = document.getElementById('filePreviewModal');
    if (!modalEl) { window.open(url, '_blank'); return; }
    const frame = document.getElementById('filePreviewFrame');
    const titleEl = document.getElementById('filePreviewTitle');
    if (titleEl) titleEl.textContent = title || '文件预览';
    if (frame) frame.src = url;
    if (bootstrap && bootstrap.Modal) {
      lastFocusedEl = document.activeElement;
      const modal = new bootstrap.Modal(modalEl);
      modalEl.addEventListener('shown.bs.modal', function(){
        const closeBtn = modalEl.querySelector('.btn-close');
        (closeBtn || modalEl).focus();
      }, { once: true });
      modalEl.addEventListener('hidden.bs.modal', function(){
        if (frame) frame.src = '';
        if (lastFocusedEl && typeof lastFocusedEl.focus === 'function') lastFocusedEl.focus();
      }, { once: true });
      modal.show();
    } else {
      window.open(url, '_blank');
    }
  }

  // Bindings
  document.addEventListener('DOMContentLoaded', function(){
    // Expose asset id and image count to JS via body data- attributes
    const assetIdNode = document.querySelector('[data-asset-id]');
    if (!assetIdNode) {
      // best-effort: attach to body if template didn't
      var body = document.body;
      if (!body.getAttribute('data-asset-id')) {
        var assetIdEl = document.querySelector('[name=asset_id]');
        if (assetIdEl) body.setAttribute('data-asset-id', assetIdEl.value);
      }
    }

    // View file buttons
    document.querySelectorAll('.js-view-file').forEach(function(btn){
      btn.setAttribute('aria-label', btn.getAttribute('title') || '查看');
      btn.addEventListener('click', async function(){
        const url = this.getAttribute('data-view-url') || '';
        const fileType = (this.getAttribute('data-file-type') || '').toLowerCase();
        const title = this.getAttribute('data-file-title') || '文件预览';

        let isPdf = fileType === 'pdf' || isLikelyPdfByUrl(url);
        if (!isPdf) {
          // Fallback: HEAD probe content type
          isPdf = await detectPdfByHead(url);
        }
        if (isPdf) openPdfInModal(url, title); else window.open(url, '_blank');
      });
      btn.addEventListener('keydown', function(e){ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); } });
    });

    // Edit/Delete file buttons (accessibility)
    document.querySelectorAll('.js-edit-file, .js-delete-file').forEach(function(btn){
      if (!btn.getAttribute('aria-label')) btn.setAttribute('aria-label', btn.getAttribute('title') || '操作');
      btn.setAttribute('tabindex', '0');
      btn.addEventListener('keydown', function(e){ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); } });
    });

    // File edit
    document.querySelectorAll('.js-edit-file').forEach(function(btn){
      btn.addEventListener('click', function(e){
        e.preventDefault();
        if (typeof editFileInfo === 'function') {
          editFileInfo(
            this.getAttribute('data-file-id'),
            this.getAttribute('data-file-title') || '',
            this.getAttribute('data-file-desc') || ''
          );
        }
      });
    });

    // File delete
    document.querySelectorAll('.js-delete-file').forEach(function(btn){
      btn.addEventListener('click', function(e){
        e.preventDefault();
        if (typeof deleteFile === 'function') {
          deleteFile(
            this.getAttribute('data-file-id'),
            this.getAttribute('data-file-title') || ''
          );
        }
      });
    });

    // Batch toggle buttons
    document.querySelectorAll('.js-toggle-batch, #batchCancelBtn').forEach(function(btn){
      btn.setAttribute('aria-controls', 'batchToolbar');
      btn.setAttribute('aria-expanded', String(batchMode));
      btn.addEventListener('click', function(){
        if (typeof toggleBatchMode === 'function') toggleBatchMode();
        this.setAttribute('aria-expanded', String(batchMode));
      });
      btn.addEventListener('keydown', function(e){ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); } });
    });

    // Batch delete
    var batchDelBtn = document.querySelector('.js-batch-delete');
    if (batchDelBtn) {
      if (!batchDelBtn.getAttribute('aria-label')) batchDelBtn.setAttribute('aria-label', '批量删除');
      batchDelBtn.addEventListener('click', function(){ if (typeof batchDeleteImages === 'function') batchDeleteImages(); });
    }

    // Checkboxes
    document.querySelectorAll('.js-image-checkbox').forEach(function(cb){
      cb.addEventListener('change', function(){ if (typeof updateBatchSelection === 'function') updateBatchSelection(); });
    });

    // Image previews
    document.querySelectorAll('.js-image-preview').forEach(function(img){
      img.setAttribute('role', 'button');
      img.setAttribute('tabindex', '0');
      img.setAttribute('aria-label', '预览图片');
      img.addEventListener('click', function(){
        const url = this.getAttribute('data-image-url') || '';
        const title = this.getAttribute('data-image-title') || '';
        if (typeof showImageModal === 'function') showImageModal(url, title);
      });
      img.addEventListener('keydown', function(e){ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); } });
    });

    // Edit / Set primary / Delete image
    document.querySelectorAll('.js-edit-image').forEach(function(a){
      a.addEventListener('click', function(e){ e.preventDefault(); if (typeof editImageInfo === 'function') editImageInfo(this.getAttribute('data-image-id'), this.getAttribute('data-image-title') || '', this.getAttribute('data-image-desc') || ''); });
    });
    document.querySelectorAll('.js-set-primary').forEach(function(a){
      a.addEventListener('click', function(e){ e.preventDefault(); if (typeof setPrimaryImage === 'function') setPrimaryImage(this.getAttribute('data-image-id')); });
    });
    document.querySelectorAll('.js-delete-image').forEach(function(a){
      a.addEventListener('click', function(e){ e.preventDefault(); if (typeof deleteImage === 'function') deleteImage(this.getAttribute('data-image-id'), this.getAttribute('data-image-title') || ''); });
    });

    // Upload previews
    const uploadImages = document.getElementById('uploadImages');
    if (uploadImages) {
      uploadImages.addEventListener('change', function(e){
        const files = Array.from(e.target.files || []);
        const previewContainer = document.getElementById('previewContainer');
        const imagesPreview = document.getElementById('imagesPreview');
        const batchSettings = document.getElementById('batchSettings');
        const uploadBtn = document.getElementById('uploadImagesBtn');
        if (previewContainer) previewContainer.innerHTML = '';
        if (files.length > 0) {
          const currentImageCount = parseInt(document.body.getAttribute('data-asset-image-count') || '0', 10);
          if (currentImageCount + files.length > 10) {
            alert(`最多只能上传10张图片，当前已有${currentImageCount}张，最多还能上传${10 - currentImageCount}张`);
            this.value = '';
            if (imagesPreview) imagesPreview.style.display = 'none';
            if (batchSettings) batchSettings.style.display = 'none';
            return;
          }
          let validFiles = [];
          files.forEach((file) => {
            if (!file.type.startsWith('image/')) { alert(`文件 "${file.name}" 不是图片格式`); return; }
            if (file.size > 2 * 1024 * 1024) { alert(`图片 "${file.name}" 大小超过2MB限制`); return; }
            validFiles.push(file);
            const reader = new FileReader();
            reader.onload = function(ev){
              const col = document.createElement('div');
              col.className = 'col-md-3 mb-2';
              col.innerHTML = `
                <div class="card">
                  <img src="${ev.target.result}" class="card-img-top" alt="预览" style="height: 120px; object-fit: cover;">
                  <div class="card-body p-2">
                    <small class="text-muted">${file.name}</small><br>
                    <small class="text-muted">${(file.size / (1024 * 1024)).toFixed(2)}MB</small>
                  </div>
                </div>`;
              if (previewContainer) previewContainer.appendChild(col);
            };
            reader.readAsDataURL(file);
          });
          if (validFiles.length > 0) {
            if (imagesPreview) imagesPreview.style.display = 'block';
            if (batchSettings) batchSettings.style.display = 'block';
            if (uploadBtn) uploadBtn.textContent = `上传 ${validFiles.length} 张图片`;
          } else {
            if (imagesPreview) imagesPreview.style.display = 'none';
            if (batchSettings) batchSettings.style.display = 'none';
            if (uploadBtn) uploadBtn.textContent = '上传图片';
          }
        } else {
          if (imagesPreview) imagesPreview.style.display = 'none';
          if (batchSettings) batchSettings.style.display = 'none';
          if (uploadBtn) uploadBtn.textContent = '上传图片';
        }
      });
    }

    const uploadFile = document.getElementById('uploadFile');
    if (uploadFile) {
      uploadFile.addEventListener('change', function(e){
        const file = e.target.files && e.target.files[0];
        const filePreview = document.getElementById('filePreview');
        if (file) {
          if (file.size > 10 * 1024 * 1024) {
            alert('文件大小不能超过10MB');
            this.value = '';
            if (filePreview) filePreview.style.display = 'none';
            return;
          }
          const titleEl = document.getElementById('fileTitle');
          if (titleEl && !titleEl.value) titleEl.value = file.name.split('.')[0];
          const fileSize = (file.size / (1024 * 1024)).toFixed(2);
          const fileType = file.name.split('.').pop().toUpperCase();
          const infoEl = document.getElementById('fileInfo');
          if (infoEl) infoEl.innerHTML = `
            <strong>文件名:</strong> ${file.name}<br>
            <strong>文件类型:</strong> ${fileType}<br>
            <strong>文件大小:</strong> ${fileSize} MB`;
          if (filePreview) filePreview.style.display = 'block';
        } else {
          if (filePreview) filePreview.style.display = 'none';
        }
      });
    }
  });
})();
